package com.test.common.config;

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;

import java.util.ArrayList;

/**
 * Spring MongoDB configuration file
 */
@Configuration
public class MongoConfig extends AbstractMongoConfiguration {

    @Value("${spring.data.mongodb.host}")
    private String host;

    @Value("${spring.data.mongodb.port}")
    private int port;

    @Value("${spring.data.mongodb.username:NA}")
    private String username;

    @Value("${spring.data.mongodb.password:NA}")
    private String password;

    @Value("${spring.data.mongodb.database}")
    private String database;


    @Bean(name = "GridFsTemplate")
    public GridFsTemplate gridFsTemplate() throws Exception {
        return new GridFsTemplate(mongoDbFactory(), mappingMongoConverter());
    }

    @Bean(name = "GridFSBucket")
    public GridFSBucket getGridFSBucket() {
        return GridFSBuckets.create(mongoClient().getDatabase(getDatabaseName()));
    }

    @Override
    public MongoClient mongoClient() {
        if (username == null || username.equals("NA")) {
            return new MongoClient(host, port);
        } else {
            return new MongoClient(new ArrayList<ServerAddress>() {{
                add(new ServerAddress(host, port));
            }}, new ArrayList<MongoCredential>() {{
                add(MongoCredential.createScramSha1Credential(username,
                        database, password.toCharArray()));
            }});
        }
    }

    @Override
    protected String getDatabaseName() {
        return database;
    }
}
